<template>
  <div class="suggestion-container">
    <van-cell
      v-for="(item, index) in suggestionList"
      :key="index"
      icon="search"
      @click="$emit('get-suggestion-value', item)"
    >
      <span slot="title" v-html="highLight(item)">{{ item }}</span>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/article.js'
import { debounce } from "lodash"
export default {
  name: 'SuggestionSearch',
  props: {
      searchValue: {
        type: String,
        default: null
  }},
  data() {
      return {
          suggestionList: []
      }
  },
  watch: {
      searchValue: {
          handler(value) {
            this.getSuggestion(value)
          },
          // watch()监听某个值（双向绑定）的变化，一旦发生变化，酒调用，immediate上来先调用一次
          immediate: true
      }
  },
  methods: {
    getSuggestion: debounce(async function() {
        const searchValue = this.searchValue
        if (!searchValue) {
        return
        }
        const { data } = await getSuggestion(this.searchValue)
        this.suggestionList = data.data.options
    }, 300),
    highLight(item) {
      console.log(item);
      const reg = new RegExp(this.searchValue, 'gi')
      return item.replace(reg, `<span style="color: #3296fa">${this.searchValue}</span>`)
    }
  }

}
</script>

<style scope lang="less">

</style>
